// Copyright 2009, Lucid Technics, LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in
// writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.

importClass(Packages.org.apache.commons.io.output.LockableFileWriter);
importClass(Packages.org.apache.commons.io.FileUtils);
importClass(Packages.org.apache.commons.io.IOUtils);
importClass(Packages.org.apache.commons.io.LineIterator);
importClass(Packages.org.apache.commons.lang.StringUtils);
importClass(Packages.java.io.File);
importClass(Packages.java.util.ArrayList);

var authFileName = SERVLET.getServletConfig().getInitParameter("rr.auth.file"),
    fileWriter,
    repositortyName,
    user,
    permission;

CONTENT_CONTEXT.type = "application/xhtml+xml";

var [svnAuthorization, errorMap] = h.populate();

if (errorMap.isEmpty() === true)
{		
	try
	{
		authFile = new File(authFileName);
		fileWriter = LockableFileWriter(authFile, true);

		repositoryName = svnAuthorization.repositoryName;
		user = svnAuthorization.user;
		permission = svnAuthorization.permission;

		//make a backup
		if(authFile.exists() === true) {
			//always create a new one so you will at least have a working
			//file somewhere along the line.  Need to clean this is up a
			//bit.
			FileUtils.copyFile(authFile, new File(authFileName + ".backup." + h.g()));
		}

		var projectFound = false,
		it = FileUtils.lineIterator(authFile, "UTF-8"),
		lines = new ArrayList(),
		line;

		while (it.hasNext() === true && projectFound === false) {
			line = it.nextLine();
			projectFound = StringUtils.contains(line, "[" + repositoryName + ":");
			if(projectFound === true) {
				lines.add(user + "=" + permission);
				IOUtils.writeLines(lines, null, fileWriter);
			}
		}

		if(projectFound === false) {
			lines.add("["+repositoryName+":/]");
			lines.add(user + "=" + permission);
			IOUtils.writeLines(lines, null, fileWriter);
		}

		CONTENT_CONTEXT.content = h.msg201();

	} catch(e){
		LOG.error("Unable to create  or modify authorization file: " + repositoryName);
		LOG.error(e);

		CONTENT_CONTEXT.content = h.msg500();
	} finally {
		try { LineIterator.closeQuietly(it); } catch(e) {}
		try { fileWriter.close(); } catch(e) { LOG.warn("Error encountered while trying to close auth file"); }
	}
}
else
{
	CONTENT_CONTEXT.content = h.msg401(errorMap);
}
